package com.smart.task;


import java.util.Observable;
import java.util.Observer;

import com.smart.data.ContactAccessor;

import android.os.AsyncTask;
import android.util.Log;

public abstract class GenericTask extends AsyncTask<TaskParam, Void, TaskResult> 
		implements Observer{
	private static final String TAG = "GenericTask";
	
	private TaskListener mTaskListener ;
	private boolean isCancelable = true;
	
	public ContactAccessor accessor ;
	
	public void setAccessor(ContactAccessor accessor) {
		this.accessor = accessor;
	}

	public TaskListener getTaskListener() {
		return mTaskListener;
	}

	public void setTaskListener(TaskListener mTaskListener) {
		this.mTaskListener = mTaskListener;
	}
	
	public void setCancelable(boolean flag) {
		isCancelable = flag;
	}

	@Override
	protected TaskResult doInBackground(TaskParam... params) {
		// TODO Auto-generated method stub
		return _doInBackground(params);
	}
	
	protected abstract TaskResult _doInBackground(TaskParam... params) ;

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		if (mTaskListener != null) {
			mTaskListener.onPreExecute(this);
		}
	}

	@Override
	protected void onPostExecute(TaskResult result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		
		if (mTaskListener != null) {
			mTaskListener.onPostExecute(this, result);
		}

	}

	@Override
	protected void onProgressUpdate(Void... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		
		if (mTaskListener != null) {
				mTaskListener.onProgressUpdate(values);
		}
	}

	@Override
	protected void onCancelled() {
		// TODO Auto-generated method stub
		super.onCancelled();
		
		if (mTaskListener != null) {
			mTaskListener.onCancelled(this);
		}
		Log.d(TAG, mTaskListener.getName() + " has been Cancelled.");
	}

	public void update(Observable o, Object arg) {
		if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) {
			if (getStatus() == GenericTask.Status.RUNNING) {
				cancel(true);
			}
		}
	}
	
}
